package com.ellecity06.cwhiskymall.view.span

import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Paint.FontMetricsInt
import android.graphics.RectF
import android.text.style.ReplacementSpan
import android.util.Log
import com.ellecity06.common.ktx.dp2px
import com.ellecity06.common.utils.logD

/**
 * @param color  背景颜色
 * @param radius 圆角半径
 */
class RadiusBackgroundSpan @JvmOverloads constructor(private val mColor: Int, private val mRadius: Int, private val textColor: Int = Color.WHITE,val textSize:Float=10f) :
    ReplacementSpan() {
    private var mSize = 0
    override fun getSize(paint: Paint, text: CharSequence, start: Int, end: Int, fm: FontMetricsInt?): Int {
        mSize = (paint.measureText(text, start, end) + 2 * mRadius).toInt()
        //mSize就是span的宽度，span有多宽，开发者可以在这里随便定义规则
        //我的规则：这里text传入的是SpannableString，start，end对应setSpan方法相关参数
        //可以根据传入起始截至位置获得截取文字的宽度，最后加上左右两个圆角的半径得到span宽度
        return mSize
    }

    override fun draw(canvas: Canvas, text: CharSequence, start: Int, end: Int, x: Float, top: Int, y: Int, bottom: Int, paint: Paint) {
//        Log.d("sdadsasdas", "text=$text,start=$start,end=$end,x=$x,y=$y,bottom=$bottom")
        paint.isAntiAlias = true
        paint.color = mColor
        val fontMetricsInt = paint.fontMetricsInt
        // 计算偏移位置，让
        val offsetY = (y + fontMetricsInt.ascent + y + fontMetricsInt.descent) / 2 - (top + bottom) / 2
//        logD("offsetY==$offsetY")
        val oval = RectF(
            x,
            (y + paint.ascent() -offsetY),
            ((x + mSize) * 1.0).toFloat(),
            (y + paint.descent() -offsetY)
        )
        //设置文字背景矩形，x为span其实左上角相对整个TextView的x值，y为span左上角相对整个View的y值。paint.ascent()获得文字上边缘，paint.descent()获得文字下边缘
        //绘制圆角矩形，第二个参数是x半径，第三个参数是y半径
        canvas.drawRoundRect(oval, mRadius.toFloat(), mRadius.toFloat(), paint)
        //恢复画笔的文字颜色
        paint.color = textColor
        val originalSize =textSize.dp2px()
        //        int originalSize = px2sp(textSize);
        paint.textSize = originalSize.toFloat()
        paint.textAlign = Paint.Align.CENTER
        val fontMetrics: Paint.FontMetrics = paint.fontMetrics
        //为基线到字体上边框的距离,即上图中的top
        val top = fontMetrics.top
        //为基线到字体下边框的距离,即上图中的bottom
        val bottom = fontMetrics.bottom
        //基线中间点的y轴计算公式
        val baseLineY = (oval.centerY() - top / 2 - bottom / 2)
        //绘制文字
        canvas.drawText(text, start, end, oval.centerX(), baseLineY, paint)
    }
}